package com.managertrade.service.impl;

import com.managertrade.dao.mysql.entity.UserFollowTrader;
import com.managertrade.dao.mysql.repository.UserFollowTraderRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Component
@Slf4j
public class TransactionalService {
    @Autowired
    private UserFollowTraderRepository userFollowTraderRepository;
    @Transactional
    public void saveNewTradersInBatch(List<UserFollowTrader> newTraders) {
        if (!CollectionUtils.isEmpty(newTraders)) {
            int batchSize = 50;
            int total = newTraders.size();
            for (int i = 0; i < total; i += batchSize) {
                int end = Math.min(i + batchSize, total);
                List<UserFollowTrader> batchList = newTraders.subList(i, end);
                userFollowTraderRepository.saveAll(batchList);
                log.info("已保存 {} 位新的交易员（本批次 {}-{}）", batchList.size(), i + 1, end);
                // 避免占用过久，可手动flush
                userFollowTraderRepository.flush();
            }
        } else {
            log.info("没有新的交易员需要保存");
        }
    }

}
